package com.kuangjia.student_ems.controller;

import com.kuangjia.student_ems.dto.PositionDTO;
import com.kuangjia.student_ems.dto.request.PositionRequest;
import com.kuangjia.student_ems.dto.response.ApiResponse;
import com.kuangjia.student_ems.service.PositionService;
import com.kuangjia.student_ems.entity.Position;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

@RestController
@RequestMapping("/positions")
public class PositionController {

    private static final Logger logger = LoggerFactory.getLogger(PositionController.class);
    
    @Autowired
    private PositionService positionService;
    
    @PostMapping
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<PositionDTO> createPosition(@Valid @RequestBody PositionRequest request) {
        try {
            return new ResponseEntity<>(positionService.createPosition(request), HttpStatus.CREATED);
        } catch (Exception e) {
            logger.error("创建岗位时发生异常，岗位名称: {}", request.getName(), e);
            throw e;
        }
    }
    
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<PositionDTO> updatePosition(@PathVariable Long id, @Valid @RequestBody PositionRequest request) {
        try {
            return ResponseEntity.ok(positionService.updatePosition(id, request));
        } catch (Exception e) {
            logger.error("更新岗位时发生异常，岗位ID: {}, 岗位名称: {}", id, request.getName(), e);
            throw e;
        }
    }
    
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deletePosition(@PathVariable Long id) {
        try {
            positionService.deletePosition(id);
            return ResponseEntity.ok(new ApiResponse<>(true, "岗位删除成功"));
        } catch (Exception e) {
            logger.error("删除岗位时发生异常，岗位ID: {}", id, e);
            throw e;
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<PositionDTO> getPositionById(@PathVariable Long id) {
        return ResponseEntity.ok(positionService.getPositionById(id));
    }
    
    @GetMapping
    public ResponseEntity<List<PositionDTO>> getAllPositions() {
        return ResponseEntity.ok(positionService.getAllPositions());
    }
    
    @GetMapping("/search")
    public ResponseEntity<List<PositionDTO>> searchPositions(@RequestParam String keyword) {
        return ResponseEntity.ok(positionService.searchPositions(keyword));
    }
    
    @GetMapping("/active")
    public ResponseEntity<List<PositionDTO>> getActivePositions() {
        return ResponseEntity.ok(positionService.getActivePositions());
    }
    
    @GetMapping("/department/{departmentId}")
    public ResponseEntity<List<PositionDTO>> getPositionsByDepartment(@PathVariable Long departmentId) {
        return ResponseEntity.ok(positionService.getPositionsByDepartment(departmentId));
    }
    
    @GetMapping("/department/{departmentId}/active")
    public ResponseEntity<List<PositionDTO>> getActivePositionsByDepartment(@PathVariable Long departmentId) {
        return ResponseEntity.ok(positionService.getActivePositionsByDepartment(departmentId));
    }
    
    @PutMapping("/{id}/toggle-status")
    @PreAuthorize("hasRole('HR_ADMIN')")
    public ResponseEntity<PositionDTO> togglePositionStatus(@PathVariable Long id) {
        return ResponseEntity.ok(positionService.togglePositionStatus(id));
    }
    
    @GetMapping("/page")
    public IPage<PositionDTO> getPositionPage(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String keyword) {
        try {
            if (pageNum < 1) pageNum = 1;
            if (pageSize < 1) pageSize = 10;
            Page<Position> page = new Page<>(pageNum, pageSize);
            return positionService.getPositionPage(page, keyword);
        } catch (Exception e) {
            e.printStackTrace();
            Page<PositionDTO> emptyPage = new Page<>();
            emptyPage.setRecords(java.util.Collections.emptyList());
            emptyPage.setTotal(0);
            return emptyPage;
        }
    }
} 